package com.hj.saapp;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.BRMicro.SerialPort;
import com.android.hdhe.uhf.reader.Tools;
import com.android.hdhe.uhf.reader.UhfReader;
import com.blankj.utilcode.utils.Utils;
import com.function.AndroidWakeLock;
import com.function.SPconfig;
import com.hj.saapp.common.manager.AppManager;
import com.hj.saapp.common.manager.NetworkManager;
import com.hj.saapp.common.utils.CrashHandler;
import com.hj.saapp.common.utils.HttpHelper;
import com.hj.saapp.common.utils.PreferencesUtils;
import com.hj.saapp.common.utils.Util;
import com.orhanobut.logger.Logger;
import com.postek.cdf.CDFPTKAndroid;
import com.pow.api.cls.RfidPower;
import com.uhf.api.cls.Reader;

import java.io.DataOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import HJ.EpcDecode.Decode;
import lib.hj.com.commonlib.bean.BaseBean;
import lib.hj.com.commonlib.manager.HttpManager;
import lib.hj.com.commonlib.utils.Constant;
import lib.hj.com.commonlib.utils.OnAsyncHttpResponse;
import lib.hj.com.commonlib.utils.Req;

/**
 * Created by "丁永泽" on 2016/8/12.
 */

public class BCDApplication extends Application {

    /**
     * 服务器接口路径
     */
    public static String Service_addr = "";
    public static String printStr = "";
    public static boolean isDevType = false;
    public static String Service_addr2 = "";
    public static String deviceAddr = "";
    public static String appPath = "";
    public static BCDApplication application;
    public static boolean isInit = false;
    public static boolean quote = false;
    public String logFile;
    private UhfReader reader; //超高频读写器
    private boolean runFlag = true;
    private boolean startFlag = false;
    InventoryThread rfidThread ;
    public String RFIDNum = "";
    public static  String ajbh = "";
    public ArrayList<String> rfidList = new ArrayList<>();

    public String addr = "";
    boolean isPostFlag = true;

    public ArrayList pArray;


    List ptList = new ArrayList();


    public static CDFPTKAndroid cdf = null;

    Iterator iiter;
    public RfidPower Rpower;
    public SPconfig spf;
    public Map<String,Reader.TAGINFO> TagsMap=new LinkedHashMap<String,Reader.TAGINFO>();//有序
    public String path;
    public int ThreadMODE=0;
    public int refreshtime=1000;
    public int Mode;
    public Map<String, String> m;
    public boolean needreconnect;
    public Reader Mreader;
    public int antportc;

    boolean autostop;
    String[] Coname=new String[]{"序号","EPC ID","次数","天线","协议","RSSI","频率","附加数据"};
    long Starttime;
    // 读线程：
    boolean isrun;
    private Thread runThread;

    public ReaderParams Rparams;
    public String Address;
    public boolean nostop=false;
    AndroidWakeLock Awl;
    private SoundPool soundPool;
    Map<String, String> h = new HashMap<String, String>();
    List<Map<String, ?>> ListMs = new ArrayList<Map<String, ?>>();




    public class ReaderParams
    {

        //save param
        public int opant;

        public List<String> invpro;
        public String opro;
        public int[] uants;
        public int readtime;
        public int sleep;

        public int checkant;
        public int[] rpow;
        public int[] wpow;

        public int region;
        public int[] frecys;
        public int frelen;

        public int session;
        public int qv;
        public int wmode;
        public int blf;
        public int maxlen;
        public int target;
        public int gen2code;
        public int gen2tari;

        public String fildata;
        public int filadr;
        public int filbank;
        public int filisinver;
        public int filenable;

        public int emdadr;
        public int emdbytec;
        public int emdbank;
        public int emdenable;

        public int antq;
        public int adataq;
        public int rhssi;
        public int invw;
        public int iso6bdeep;
        public int iso6bdel;
        public int iso6bblf;
        public int option;
        //other params

        public String password;
        public int optime;
        public ReaderParams()
        {
            opant=1;
            invpro=new ArrayList<String>();
            invpro.add("GEN2");
            uants=new int[1];
            uants[0]=1;
            sleep=0;
            readtime=50;
            optime=1000;
            opro="GEN2";
            checkant=1;
            rpow=new int[]{2700,2000,2000,2000};
            wpow=new int[]{2000,2000,2000,2000};
            region=1;
            frelen=0;
            session=0;
            qv=-1;
            wmode=0;
            blf=0;
            maxlen=0;
            target=0;
            gen2code=2;
            gen2tari=0;

            fildata="";
            filadr=32;
            filbank=1;
            filisinver=0;
            filenable=0;

            emdadr=0;
            emdbytec=0;
            emdbank=1;
            emdenable=0;

            adataq=0;
            rhssi=1;
            invw=0;
            iso6bdeep=0;
            iso6bdel=0;
            iso6bblf=0;
            option=0;
        }
    }



    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        if (!isInit) {

            isInit = true;
            Utils.init(this);
            initData();
            if (isDevType) {

                initRF();
            }


        }

    }

    private void initData() {

        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());

        BCDApplication.printStr =  PreferencesUtils.getInstance().getString(BCDApplication.getApp(),"ptintStr", "");
        BCDApplication.isDevType =  PreferencesUtils.getInstance().getBoolean(BCDApplication.getApp(), "isDevType", false);
        deviceAddr = PreferencesUtils.getInstance().getString(BCDApplication.getApp(), Constant.deviceAddr, null);
        pArray = new ArrayList();
    }

    public static BCDApplication getApp() {
        return application;
    }


    public static void call(String mobile) {
        if (!TextUtils.isEmpty(mobile)) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile));
            AppManager.getAppManager().getActivity().startActivity(intent);
        }
    }

    public static String[] getDate() {


        String date[] = new String[2];

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 3));//获取当前时间
        String str = formatter.format(curDate);

        Date end = new Date(System.currentTimeMillis());//获取当前时间
        String str2 = formatter.format(end);

        date[0] = str + " 00:00:00";
        date[1] = str2 + " 23:59:59";
        return date;

    }







    /**
     * 盘存线程
     *
     * @author Administrator
     */
    class InventoryThread extends Thread {
        private List<byte[]> epcList;

        @Override
        public void run() {
            super.run();
            while (runFlag) {

                if (startFlag) {

                    epcList = reader.inventoryRealTime(); //实时盘存
                    if (epcList != null && !epcList.isEmpty()) {


                        for (byte[] epc : epcList) {
                            boolean isHas = false;
                            String epcStr = Tools.Bytes2HexString(epc, epc.length);
                            for (int i = 0; i < rfidList.size(); i++) {

                                String temp = rfidList.get(i);
                                if (temp.equals(epcStr)) {
                                    isHas = true;
                                    break;
                                }

                            }
                            if (!isHas)
                            {
                                rfidList.add(epcStr);
                                Util.play(1, 0);
                                String rfidTemp = epcStr;
                                String rfid = Decode.GetDecodeEpc(epcStr);
                                if (!TextUtils.isEmpty(rfid))
                                {
                                    rfidTemp = rfid;
                                }


                            }

                        }
                    }
                    epcList = null;
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }else
                {
                    RFIDNum = "";
                }
            }
        }
    }



//    Handler handler = new Handler(Looper.myLooper())
//    {
//        @Override
//        public void handleMessage(Message msg) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//
//                    if (iiter.hasNext()) {
//
//                            String data = (String) iiter.next();
//                            Map<String, String> map = new HashMap<>();
//                            map.put("data", data);
//
//                            HttpHelper.postPt(new OnAsyncHttpResponse() {
//                                @Override
//                                public void onSuccess(BaseBean paramObject) {
//                                    isPostFlag = true;
//                                    Logger.e("pArray.remove");
//                                    iiter.remove();
//                                    handler2.sendEmptyMessage(1);
//
//                                }
//
//                                @Override
//                                public void onFailure(int paramInt, String paramString) {
//                                    handler2.sendEmptyMessage(1);
//
//                                }
//
//                                @Override
//                                public void offLine(Req req) {
//
//                                }
//                            }, map);
//
//
//                    }
//
//
//                }
//            }).start();
//
//        }
//    };
//
//    Handler handler2 = new Handler(Looper.myLooper())
//    {
//        @Override
//        public void handleMessage(Message msg) {
//            if (NetworkManager.getNetworkManager().isNetworkConnected() && iiter != null) {
//
//                if (iiter.hasNext()) {
//                    handler.sendEmptyMessage(1);
//                }
//
//            }
//
//        }
//    };



    public void setDeviceAddr(String deviceAddr) {

        BCDApplication.deviceAddr = deviceAddr;
        PreferencesUtils.getInstance().putString(BCDApplication.getApp(), Constant.deviceAddr, deviceAddr);

    }




    private void connect() {

        SerialPort serialPort = new SerialPort();
        serialPort.zigbee_poweron();
        RfidPower.PDATYPE PT= RfidPower.PDATYPE.valueOf(13);
        BCDApplication.getApp().Rpower=new RfidPower(PT);


        boolean blen=BCDApplication.getApp().Rpower.PowerUp();

        HttpManager.myLog("上电","上电");

        blen = true;


        if(!blen)
            return;

        Reader.READER_ERR er=BCDApplication.getApp().Mreader.InitReader_Notype("/dev/ttyMT1", 1);
        //READER_ERR er=myapp.Mreader.InitReader(ip, Reader_Type.MODULE_ONE_ANT);
        if(er== Reader.READER_ERR.MT_OK_ERR)
        {
            BCDApplication.getApp().needreconnect=false;
            BCDApplication.getApp().spf.SaveString("PDATYPE", String.valueOf(13));
            BCDApplication.getApp().spf.SaveString("ADDRESS", "/dev/ttyMT1");
            BCDApplication.getApp().spf.SaveString("ANTPORT", "0");
            BCDApplication.getApp().antportc=1;
            HttpManager.myLog("连接成功","连接成功");

            ConnectHandleUI();
            BCDApplication.getApp().Address="/dev/ttyMT1";

        }
    }

    private void ConnectHandleUI()
    {
        try
        {
            Reader.READER_ERR er;
            BCDApplication.getApp().Rparams= BCDApplication.getApp().spf.ReadReaderParams();

            if( BCDApplication.getApp().Rparams.invpro.size()<1)
                BCDApplication.getApp().Rparams.invpro.add("GEN2");

            List<Reader.SL_TagProtocol> ltp=new ArrayList<Reader.SL_TagProtocol>();
            for(int i=0;i< BCDApplication.getApp().Rparams.invpro.size();i++)
            {  if( BCDApplication.getApp().Rparams.invpro.get(i).equals("GEN2"))
            { ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_GEN2);

            }
            else if( BCDApplication.getApp().Rparams.invpro.get(i).equals("6B"))
            {
                ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_ISO180006B);

            }
            else if( BCDApplication.getApp().Rparams.invpro.get(i).equals("IPX64"))
            {
                ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_IPX64);

            }
            else if( BCDApplication.getApp().Rparams.invpro.get(i).equals("IPX256"))
            {
                ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_IPX256);

            }
            }

            Reader.Inv_Potls_ST ipst= BCDApplication.getApp().Mreader.new Inv_Potls_ST();
            ipst.potlcnt=ltp.size();
            ipst.potls=new Reader.Inv_Potl[ipst.potlcnt];
            Reader.SL_TagProtocol[] stp=ltp.toArray(new Reader.SL_TagProtocol[ipst.potlcnt]);
            for(int i=0;i<ipst.potlcnt;i++)
            {
                Reader.Inv_Potl ipl= BCDApplication.getApp().Mreader.new Inv_Potl();
                ipl.weight=30;
                ipl.potl=stp[i];
                ipst.potls[0]=ipl;
            }

            er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_INVPOTL, ipst);
            Log.d("MYINFO", "Connected set pro:"+er.toString());

            er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_READER_IS_CHK_ANT,
                    new int[]{ BCDApplication.getApp().Rparams.checkant});
            Log.d("MYINFO", "Connected set checkant:"+er.toString());


            Reader.AntPowerConf apcf= BCDApplication.getApp().Mreader.new AntPowerConf();
            apcf.antcnt= BCDApplication.getApp().antportc;
            for(int i=0;i<apcf.antcnt;i++)
            {
                Reader.AntPower jaap= BCDApplication.getApp().Mreader.new AntPower();
                jaap.antid=i+1;
                jaap.readPower =(short) BCDApplication.getApp().Rparams.rpow[i];
                jaap.writePower=(short) BCDApplication.getApp().Rparams.wpow[i];
                apcf.Powers[i]=jaap;
            }

            BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_RF_ANTPOWER, apcf);

            Reader.Region_Conf rre;
            switch( BCDApplication.getApp().Rparams.region)
            {
                case 0:
                    rre = Reader.Region_Conf.RG_PRC;
                    break;
                case 1:
                    rre = Reader.Region_Conf.RG_NA;
                    break;
                case 2:
                    rre= Reader.Region_Conf.RG_NONE;
                    break;
                case 3:
                    rre= Reader.Region_Conf.RG_KR;
                    break;
                case 4:
                    rre= Reader.Region_Conf.RG_EU;
                    break;
                case 5:
                case 6:
                case 7:
                case 8:
                default:
                    rre= Reader.Region_Conf.RG_NONE;
                    break;
            }
            if(rre!= Reader.Region_Conf.RG_NONE)
            {
                er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_FREQUENCY_REGION,rre);
            }

            if( BCDApplication.getApp().Rparams.frelen>0)
            {

                Reader.HoptableData_ST hdst= BCDApplication.getApp().Mreader.new HoptableData_ST();
                hdst.lenhtb= BCDApplication.getApp().Rparams.frelen;
                hdst.htb= BCDApplication.getApp().Rparams.frecys;
                er= BCDApplication.getApp().Mreader.ParamSet
                        (Reader.Mtr_Param.MTR_PARAM_FREQUENCY_HOPTABLE,hdst);
            }


            er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
                    new int[]{ BCDApplication.getApp().Rparams.session});
            er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_Q,
                    new int[]{ BCDApplication.getApp().Rparams.qv});
            er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_WRITEMODE,
                    new int[]{ BCDApplication.getApp().Rparams.wmode});
            er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_MAXEPCLEN,
                    new int[]{ BCDApplication.getApp().Rparams.maxlen});
            er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_TARGET,
                    new int[]{ BCDApplication.getApp().Rparams.target});

            if( BCDApplication.getApp().Rparams.filenable==1)
            {
                Reader.TagFilter_ST tfst= BCDApplication.getApp().Mreader.new TagFilter_ST();
                tfst.bank= BCDApplication.getApp().Rparams.filbank;
                tfst.fdata=new byte[ BCDApplication.getApp().Rparams.fildata.length()/2];
                BCDApplication.getApp().Mreader.Str2Hex( BCDApplication.getApp().Rparams.fildata,
                        BCDApplication.getApp().Rparams.fildata.length(), tfst.fdata);
                tfst.flen=tfst.fdata.length*8;
                tfst.startaddr= BCDApplication.getApp().Rparams.filadr;
                tfst.isInvert= BCDApplication.getApp().Rparams.filisinver;

                BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_FILTER, tfst);
            }

            if( BCDApplication.getApp().Rparams.emdenable==1)
            {
                Reader.EmbededData_ST edst =  BCDApplication.getApp().Mreader.new EmbededData_ST();

                edst.accesspwd=null;
                edst.bank= BCDApplication.getApp().Rparams.emdbank;
                edst.startaddr= BCDApplication.getApp().Rparams.emdadr;
                edst.bytecnt= BCDApplication.getApp().Rparams.emdbytec;
                edst.accesspwd=null;

                er= BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA,
                        edst);
            }

            er= BCDApplication.getApp().Mreader.ParamSet
                    (Reader.Mtr_Param.MTR_PARAM_TAGDATA_UNIQUEBYEMDDATA,
                            new int[]{ BCDApplication.getApp().Rparams.adataq});
            er= BCDApplication.getApp().Mreader.ParamSet
                    (Reader.Mtr_Param.MTR_PARAM_TAGDATA_RECORDHIGHESTRSSI,
                            new int[]{ BCDApplication.getApp().Rparams.rhssi});
            er= BCDApplication.getApp().Mreader.ParamSet
                    (Reader.Mtr_Param.MTR_PARAM_TAG_SEARCH_MODE,
                            new int[]{ BCDApplication.getApp().Rparams.invw});


            Reader.HardwareDetails val= BCDApplication.getApp().Mreader.new HardwareDetails();
            er= BCDApplication.getApp().Mreader.GetHardwareDetails(val);


        }catch(Exception ex)
        {

        }

    }

    public void start_read(){
        try{



            boolean bl = true;
            if(BCDApplication.getApp().needreconnect)
            {
                int c=0;
                do{
                    bl=reconnect();
                    if(!bl)
                    {

                    }
                    c++;
                    if(c>0)
                        break;
                }
                while(true);
            }
            if(!bl)
                return;

            if(BCDApplication.getApp().nostop)
            {
                Reader.READER_ERR er=BCDApplication.getApp().Mreader.AsyncStartReading(BCDApplication.getApp().Rparams.uants,
                        BCDApplication.getApp().Rparams.uants.length, BCDApplication.getApp().Rparams.option);
                if(er!= Reader.READER_ERR.MT_OK_ERR)
                {
                    Toast.makeText(AppManager.getAppManager().getActivity(), "不停顿盘点启动失败",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
            }

//            if(BCDApplication.getApp().ThreadMODE==0)
//
//                    handler.postDelayed(runnable_MainActivity,0);
//
//            else
//            {
//                isrun=true;
//                runThread=new Thread(runnable_alone);
//                runThread.start();
//                handler.postDelayed(runnable_refreshlist, 0);
//            }
            Starttime=0;
            BCDApplication.getApp().TagsMap.clear();

            Awl.WakeLock();
        }catch(Exception ex)
        {

        }
    }
    public void stop_read(){
        Awl.ReleaseWakeLock();
        if (BCDApplication.getApp().nostop) {
            Log.d("MYINFO", "stop---");
            Reader.READER_ERR er = BCDApplication.getApp().Mreader.AsyncStopReading();
            if (er != Reader.READER_ERR.MT_OK_ERR) {

                return;
            }
        }
//
//        if (BCDApplication.getApp().ThreadMODE == 0)
//            handler.removeCallbacks(runnable_MainActivity);
//        else {
//            isrun = false;
//            try {
//                runThread.join();
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            handler.removeCallbacks(runnable_refreshlist);
//        }

        if (BCDApplication.getApp().Rpower.GetType() == RfidPower.PDATYPE.SCAN_ALPS_ANDROID_CUIUS2) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Awl.ReleaseWakeLock();
        autostop = false;

        BCDApplication.getApp().TagsMap.putAll(TagsMap);


    }

    private boolean reconnect()
    {
        Log.d("MYINFO", "reconenct");
        boolean blen=BCDApplication.getApp().Rpower.PowerUp();
        if(!blen)
            return false;

        Reader.READER_ERR er=BCDApplication.getApp().Mreader.InitReader_Notype(BCDApplication.getApp().Address, BCDApplication.getApp().antportc);
        if(er== Reader.READER_ERR.MT_OK_ERR)
        {

            BCDApplication.getApp().needreconnect=false;
            try
            {

                BCDApplication.getApp().Rparams=BCDApplication.getApp().spf.ReadReaderParams();

                if(BCDApplication.getApp().Rparams.invpro.size()<1)
                    BCDApplication.getApp().Rparams.invpro.add("GEN2");

                List<Reader.SL_TagProtocol> ltp=new ArrayList<Reader.SL_TagProtocol>();
                for(int i=0;i<BCDApplication.getApp().Rparams.invpro.size();i++)
                {  if(BCDApplication.getApp().Rparams.invpro.get(i).equals("GEN2"))
                { ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_GEN2);

                }
                else if(BCDApplication.getApp().Rparams.invpro.get(i).equals("6B"))
                {
                    ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_ISO180006B);

                }
                else if(BCDApplication.getApp().Rparams.invpro.get(i).equals("IPX64"))
                {
                    ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_IPX64);

                }
                else if(BCDApplication.getApp().Rparams.invpro.get(i).equals("IPX256"))
                {
                    ltp.add(Reader.SL_TagProtocol.SL_TAG_PROTOCOL_IPX256);

                }
                }

                Reader.Inv_Potls_ST ipst=BCDApplication.getApp().Mreader.new Inv_Potls_ST();
                ipst.potlcnt=ltp.size();
                ipst.potls=new Reader.Inv_Potl[ipst.potlcnt];
                Reader.SL_TagProtocol[] stp=ltp.toArray(new Reader.SL_TagProtocol[ipst.potlcnt]);
                for(int i=0;i<ipst.potlcnt;i++)
                {
                    Reader.Inv_Potl ipl=BCDApplication.getApp().Mreader.new Inv_Potl();
                    ipl.weight=30;
                    ipl.potl=stp[i];
                    ipst.potls[0]=ipl;
                }

                er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_INVPOTL, ipst);


                er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_READER_IS_CHK_ANT,
                        new int[]{BCDApplication.getApp().Rparams.checkant});


                Reader.AntPowerConf apcf=BCDApplication.getApp().Mreader.new AntPowerConf();
                apcf.antcnt=BCDApplication.getApp().antportc;
                for(int i=0;i<apcf.antcnt;i++)
                {
                    Reader.AntPower jaap=BCDApplication.getApp().Mreader.new AntPower();
                    jaap.antid=i+1;
                    jaap.readPower =(short)BCDApplication.getApp().Rparams.rpow[i];
                    jaap.writePower=(short)BCDApplication.getApp().Rparams.wpow[i];
                    apcf.Powers[i]=jaap;
                }

                BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_RF_ANTPOWER, apcf);

                Reader.Region_Conf rre;
                switch(BCDApplication.getApp().Rparams.region)
                {
                    case 0:
                        rre = Reader.Region_Conf.RG_PRC;
                        break;
                    case 1:
                        rre = Reader.Region_Conf.RG_NA;
                        break;
                    case 2:
                        rre= Reader.Region_Conf.RG_NONE;
                        break;
                    case 3:
                        rre= Reader.Region_Conf.RG_KR;
                        break;
                    case 4:
                        rre= Reader.Region_Conf.RG_EU;
                        break;
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    default:
                        rre= Reader.Region_Conf.RG_NONE;
                        break;
                }
                if(rre!= Reader.Region_Conf.RG_NONE)
                {
                    er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_FREQUENCY_REGION,rre);
                }

                if(BCDApplication.getApp().Rparams.frelen>0)
                {

                    Reader.HoptableData_ST hdst=BCDApplication.getApp().Mreader.new HoptableData_ST();
                    hdst.lenhtb=BCDApplication.getApp().Rparams.frelen;
                    hdst.htb=BCDApplication.getApp().Rparams.frecys;
                    er=BCDApplication.getApp().Mreader.ParamSet
                            (Reader.Mtr_Param.MTR_PARAM_FREQUENCY_HOPTABLE,hdst);
                }

                er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
                        new int[]{BCDApplication.getApp().Rparams.session});
                er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_Q,
                        new int[]{BCDApplication.getApp().Rparams.qv});
                er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_WRITEMODE,
                        new int[]{BCDApplication.getApp().Rparams.wmode});
                er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_MAXEPCLEN,
                        new int[]{BCDApplication.getApp().Rparams.maxlen});
                er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_POTL_GEN2_TARGET,
                        new int[]{BCDApplication.getApp().Rparams.target});

                if(BCDApplication.getApp().Rparams.filenable==1)
                {
                    Reader.TagFilter_ST tfst=BCDApplication.getApp().Mreader.new TagFilter_ST();
                    tfst.bank=BCDApplication.getApp().Rparams.filbank;
                    tfst.fdata=new byte[BCDApplication.getApp().Rparams.fildata.length()/2];
                    BCDApplication.getApp().Mreader.Str2Hex(BCDApplication.getApp().Rparams.fildata,
                            BCDApplication.getApp().Rparams.fildata.length(), tfst.fdata);
                    tfst.flen=tfst.fdata.length*8;
                    tfst.startaddr=BCDApplication.getApp().Rparams.filadr;
                    tfst.isInvert=BCDApplication.getApp().Rparams.filisinver;

                    BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_FILTER, tfst);
                }

                if(BCDApplication.getApp().Rparams.emdenable==1)
                {
                    Reader.EmbededData_ST edst = BCDApplication.getApp().Mreader.new EmbededData_ST();

                    edst.accesspwd=null;
                    edst.bank=BCDApplication.getApp().Rparams.emdbank;
                    edst.startaddr=BCDApplication.getApp().Rparams.emdadr;
                    edst.bytecnt=BCDApplication.getApp().Rparams.emdbytec;
                    edst.accesspwd=null;

                    er=BCDApplication.getApp().Mreader.ParamSet(Reader.Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA,
                            edst);
                }

                er=BCDApplication.getApp().Mreader.ParamSet
                        (Reader.Mtr_Param.MTR_PARAM_TAGDATA_UNIQUEBYEMDDATA,
                                new int[]{BCDApplication.getApp().Rparams.adataq});
                er=BCDApplication.getApp().Mreader.ParamSet
                        (Reader.Mtr_Param.MTR_PARAM_TAGDATA_RECORDHIGHESTRSSI,
                                new int[]{BCDApplication.getApp().Rparams.rhssi});
                er=BCDApplication.getApp().Mreader.ParamSet
                        (Reader.Mtr_Param.MTR_PARAM_TAG_SEARCH_MODE,
                                new int[]{BCDApplication.getApp().Rparams.invw});

            } catch (Exception ex) {
                Log.d("MYINFO",
                        ex.getMessage() + ex.toString() + ex.getStackTrace());
            }
        }
        else
            return false;

        return true;
    }


//    private Runnable runnable_MainActivity = new Runnable() {
//        @Override
//        public void run() {
//
//            String[] tag = null;
//            int[] tagcnt = new int[1];
//            tagcnt[0] = 0;
//
//            int streadt = 0, enreadt = 0;
//            synchronized (this) {
//                // Log.d("MYINFO", "ManActivity..1");
//                Reader.READER_ERR er;
//                streadt = (int) System.currentTimeMillis();
//                if (BCDApplication.getApp().nostop) {
//                    er = BCDApplication.getApp().Mreader.AsyncGetTagCount(tagcnt);
//                } else {
//                    er = BCDApplication.getApp().Mreader.TagInventory_Raw(BCDApplication.getApp().Rparams.uants,
//                            BCDApplication.getApp().Rparams.uants.length,
//                            (short) BCDApplication.getApp().Rparams.readtime, tagcnt);
//                }
//
//                if (er == Reader.READER_ERR.MT_OK_ERR) {
//                    if (tagcnt[0] > 0) {
//                        tag = new String[tagcnt[0]];
//                        for (int i = 0; i < tagcnt[0]; i++) {
//                            Reader.TAGINFO tfs = BCDApplication.getApp().Mreader.new TAGINFO();
//                            if (BCDApplication.getApp().Rpower.GetType() == RfidPower.PDATYPE.SCAN_ALPS_ANDROID_CUIUS2) {
//                                try {
//                                    Thread.sleep(1000);
//                                } catch (InterruptedException e) {
//                                    // TODO Auto-generated catch block
//                                    e.printStackTrace();
//                                }
//                            }
//                            if (BCDApplication.getApp().nostop)
//                                er=BCDApplication.getApp().Mreader.AsyncGetNextTag(tfs);
//                            else
//                                er = BCDApplication.getApp().Mreader.GetNextTag(tfs);
//
//                            //Log.d("MYINFO","get tag index:" + String.valueOf(i)+ " er:" + er.toString());
//                            if (er == Reader.READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET) {
//
//
//                                BCDApplication.getApp().needreconnect = true;
//
//                                autostop = true;
//                            }
//
//                            // Log.d("MYINFO","debug gettag:"+er.toString());
//                            // Log.d("MYINFO","debug tag:"+Reader.bytes_Hexstr(tfs.EpcId));
//
//                            if (er == Reader.READER_ERR.MT_OK_ERR) {
//
//                                tag[i] = Reader.bytes_Hexstr(tfs.EpcId);
//
//                                if (!TagsMap.containsKey(tag[i]))
//                                {
//                                    TagsMap.put(tag[i], tfs);
//
//                                    //show
//                                    Map<String, String> m = new HashMap<String, String>();
//                                    m.put(Coname[0], String.valueOf(TagsMap.size()));
//
//                                    String epcstr = Reader
//                                            .bytes_Hexstr(tfs.EpcId);
//                                    if (epcstr.length() < 24)
//                                        epcstr = String.format("%-24s", epcstr);
//
//
//                                    Logger.e(epcstr);
//                                    m.put(Coname[1], epcstr);
//                                    String cs = m.get("次数");
//                                    if (cs == null)
//                                        cs = "0";
//                                    int isc = Integer.parseInt(cs) + tfs.ReadCnt;
//
//                                    m.put(Coname[2], String.valueOf(isc));
//                                    m.put(Coname[3],
//                                            String.valueOf(tfs.AntennaID));
//                                    m.put(Coname[4], "");
//                                    m.put(Coname[5], String.valueOf(tfs.RSSI));
//                                    m.put(Coname[6],
//                                            String.valueOf(tfs.Frequency));
//
//                                    if (tfs.EmbededDatalen > 0) {
//                                        char[] out = new char[tfs.EmbededDatalen * 2];
//                                        BCDApplication.getApp().Mreader.Hex2Str(tfs.EmbededData,
//                                                tfs.EmbededDatalen, out);
//                                        m.put(Coname[7], String.valueOf(out));
//
//                                    } else
//                                        m.put(Coname[7], "                 ");
//
//
//
//                                    String rfidTemp = epcstr;
//                                    String rfid = Decode.GetDecodeEpc(rfidTemp);
//                                    if (!TextUtils.isEmpty(rfid))
//                                    {
//                                        rfidTemp = rfid;
//                                    }
//                                    soundPool.play(1, 1, 1, 0, 0, 1);
//
//
//                                }
//                                else {
//                                    Reader.TAGINFO tf = TagsMap.get(tag[i]);
//
//                                    String epcstr = tag[i];
//                                    if (epcstr.length() < 24)
//                                        epcstr = String.format("%-24s", epcstr);
//
//                                    for (int k = 0; k < ListMs.size(); k++) {
//                                        Map<String, String> m = (Map<String, String>) ListMs
//                                                .get(k);
//                                        if (m.get(Coname[1]).equals(epcstr)) {
//                                            tf.ReadCnt += tfs.ReadCnt;
//                                            tf.RSSI = tfs.RSSI;
//                                            tf.Frequency = tfs.Frequency;
//
//                                            m.put(Coname[2],
//                                                    String.valueOf(tf.ReadCnt));
//                                            m.put(Coname[5],
//                                                    String.valueOf(tf.RSSI));
//                                            m.put(Coname[6],
//                                                    String.valueOf(tf.Frequency));
//                                            break;
//                                        }
//                                    }
//                                }
//
//                            } else
//                                break;
//                        }
//
//                        enreadt = (int) System.currentTimeMillis();
//
//
//                    }
//
//                } else {
//
//                    if (er == Reader.READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET) {
//
//                        BCDApplication.getApp().needreconnect = true;
//
//                        autostop = true;
//                    } else
//                        handler.postDelayed(this, BCDApplication.getApp().Rparams.sleep);
//                    return;
//
//                }
//            }
//
//            if (tag == null) {
//                tag = new String[0];
//            } else {
//
//                if (!BCDApplication.getApp().nostop) {
//
//                } else {
//                    {
//
//                        Starttime = (int) System.currentTimeMillis();
//                    }
//                }
//            }
//            int cll = TagsMap.size();
//            if (cll < 0)
//                cll = 0;
//
//
//            handler.postDelayed(this, BCDApplication.getApp().Rparams.sleep);
//        }
//    };
//    private Runnable runnable_refreshlist = new Runnable( ) {
//        @Override
//        public void run ( ) {
//
//            handler.postDelayed(this,BCDApplication.getApp().refreshtime);
//        }
//    };
//
//    private Runnable runnable_alone = new Runnable( ) {
//        @Override
//        public void run ( ) {
//
//            while(isrun){
//                String[] tag = null;
//
//                int[] tagcnt=new int[1];
//
//                tagcnt[0]=0;
//
//
//                Reader.READER_ERR er=BCDApplication.getApp().Mreader.TagInventory_Raw
//                        (BCDApplication.getApp().Rparams.uants, BCDApplication.getApp().Rparams.uants.length,
//                                (short) BCDApplication.getApp().Rparams.readtime, tagcnt);
//
//
//                if(er== Reader.READER_ERR.MT_OK_ERR)
//                {
//
//                    if(tagcnt[0]>0)
//                    {
//                        soundPool.play(1,1, 1, 0, 0, 1);
//                        tag=new String[tagcnt[0]];
//
//                        synchronized (this)
//                        {
//                            for(int i=0;i<tagcnt[0];i++)
//                            {
//
//                                Reader.TAGINFO tfs=BCDApplication.getApp().Mreader.new TAGINFO();
//                                if(BCDApplication.getApp().Rpower.GetType()== RfidPower.PDATYPE.SCAN_ALPS_ANDROID_CUIUS2)
//                                {
//                                    try {
//                                        Thread.sleep(1000);
//                                    } catch (InterruptedException e) {
//                                        // TODO Auto-generated catch block
//                                        e.printStackTrace();
//                                    }
//                                }
//                                er=BCDApplication.getApp().Mreader.GetNextTag(tfs);
//                                Log.d("MYINFO","get tag index:"+String.valueOf(i)+" er:"+er.toString());
//                                if(er== Reader.READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET)
//                                {
//                                    Message msg2 = new Message();
//                                    msg2.what = 1;
//                                    Bundle bundle2 = new Bundle();
//                                    bundle2.putString("Msg_error_1", "error:"+String.valueOf(er.value())+er.toString());
//                                    msg2.setData(bundle2);
//                                    handler2.sendMessage(msg2);
//                                    isrun=false;
//                                    BCDApplication.getApp().needreconnect=true;
//                                }
//
//
//
//                                if (er == Reader.READER_ERR.MT_OK_ERR) {
//                                    tag[i] = Reader.bytes_Hexstr(tfs.EpcId);
//                                    soundPool.play(1, 1, 1, 0, 0, 1);
//
//                                    if(!TagsMap.containsKey(tag[i]))
//                                    {
//                                        TagsMap.put(tag[i],tfs);
//
//                                    }
//
//                                    else
//                                    {
//                                        Reader.TAGINFO tf=TagsMap.get(tag[i]);
//                                        tf.ReadCnt+=tfs.ReadCnt;
//                                        tf.RSSI=tfs.RSSI;
//                                        tf.Frequency=tfs.Frequency;
//                                    }
//
//
//                                }
//                                else
//                                    break;
//                            }
//                        }
//
//                    }
//
//                }
//                else
//                {
//                    try {
//                        Thread.sleep(BCDApplication.getApp().Rparams.sleep);
//                    } catch (InterruptedException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                    Message msg = new Message();
//
//                    Bundle bundle = new Bundle();
//                    bundle.putString("Msg_error_2", "error:"+String.valueOf(er.value())+" "+er.toString());
//                    msg.setData(bundle);
//
//
//                    if(er== Reader.READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET)
//                    {
//                        BCDApplication.getApp().needreconnect=true;
//                        isrun=false;
//                        msg.what=1;
//                    }
//                    else
//                    {
//                        msg.what = 2;
//                    }
//                    handler2.sendMessage(msg);
//                    continue;
//                }
//
//                if(tag==null)
//                {
//                    tag=new String[0];
//                }
//
//                if(tagcnt[0]>0)
//                { Message msg = new Message();
//                    Bundle bundle = new Bundle();
//                    msg.what = 0;
//                    bundle.putString("Msg_cnt", (String.valueOf(tagcnt[0])));
//                    synchronized (this)
//                    {
//                        bundle.putString("Msg_all", (String.valueOf(TagsMap.size())));
//                    }
//                    msg.setData(bundle);
//                    handler2.sendMessage(msg);
//                }
//                try {
//                    Thread.sleep(BCDApplication.getApp().Rparams.sleep);
//                } catch (InterruptedException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//        }
//    };

    public void initRF() {
        String apkRoot="chmod 777 "+getPackageCodePath();

        runRootCommand(apkRoot);

        soundPool= new SoundPool(10, AudioManager.STREAM_SYSTEM,5);
        soundPool.load(this,R.raw.beep51,1);
        BCDApplication.getApp().Mreader=new Reader();
        BCDApplication.getApp().Rparams=BCDApplication.getApp().new ReaderParams();
        for (int i = 0; i < Coname.length; i++)
        {
            h.put(Coname[i], Coname[i]);
        }


        BCDApplication.getApp().needreconnect=false;

        BCDApplication.getApp().Mreader=new Reader();

        BCDApplication.getApp().spf=new SPconfig(this);
        Awl=new AndroidWakeLock((PowerManager) getSystemService(Context.POWER_SERVICE));

        connect();
    }
    public static boolean runRootCommand(String command) {
        Process process = null;
        DataOutputStream os = null;
        try {
            Process process2 = Runtime.getRuntime().exec("su");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            process = Runtime.getRuntime().exec("sh");//Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            Log.d("Phone Link",  "su root - the device is not rooted,  error message： " + e.getMessage());
            return false;
        } finally {
            try {
                if(null != os) {
                    os.close();
                }
                if(null != process) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    public String getFormatDate(String s) {


        String sDate = s;
        try
        {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sDate=sdf.format(s);
            sDate+= s.substring(s.length()-3,s.length());
        }
        catch (Exception e)
        {
            sDate = s;
        }


        return sDate;

    }
}
